package cn.felord.socket.api;

import cn.felord.socket.core.SimpleWebSocketMessagingTemplate;
import cn.felord.socket.messaging.SimpleMessage;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * The type Ws controller.
 *
 * @author dax
 * @since 2019 /4/21 20:58
 */
@Slf4j
@RestController
@RequestMapping("/ws")
public class WsController {
    /**
     * The Socket io service.
     */
    @Resource
    SimpleWebSocketMessagingTemplate socketIOService;
    @Resource
    SocketIOServer socketIOServer;


    /**
     * Send.
     */
    @GetMapping("/broadcast")
    public void send() {
        SimpleMessage<String> stringSimpleMessage = new SimpleMessage<>();
        stringSimpleMessage.setFrom("SERVER");
        stringSimpleMessage.setPayload("消息来自服务器推送");

        socketIOService.broadcast("/test/push", stringSimpleMessage);

    }

    /**
     * Send to.
     */
    @GetMapping("/to")
    public void sendTo() {
        SimpleMessage<String> stringSimpleMessage = new SimpleMessage<>();
        stringSimpleMessage.setFrom("Jack");
        stringSimpleMessage.setPayload("你好");
        stringSimpleMessage.setTo("Lucy");

        socketIOService.sendToUser("push", stringSimpleMessage);

    }

    /**
     * On open.
     *
     * @param client the client
     */
    @OnConnect
    public void onOpen(SocketIOClient client) {
        String name = client.getNamespace().getName();
        log.info("Namespace ---> {}", name);

    }


    /**
     * On event.
     *
     * @param client  the client
     * @param request the request
     * @param data    the data
     */
    @OnEvent(value = "push")
    public void onEvent(SocketIOClient client, AckRequest request, SimpleMessage data) throws JsonProcessingException {
        String name = client.getNamespace().getName();
        System.out.println("name = " + name);
        ObjectMapper objectMapper = new ObjectMapper();

        String value = objectMapper.writeValueAsString(data);
        log.info(value);

    }


}
